package com.harvey.metrics.metric.gauge;

import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricRegistry;
import com.harvey.metrics.metric.BaseExample;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

/**
 * @author harvey
 * @Description
 * @date 2020-04-08 09:04
 * @since
 */

public class SimpleGauge extends BaseExample {

    private static final MetricRegistry metricRegistry = new MetricRegistry();

    private static final ConsoleReporter reporter = ConsoleReporter.forRegistry(metricRegistry)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.SECONDS)
            .build();

    private static final BlockingDeque<Long> queue = new LinkedBlockingDeque<>(1_000);


    public static void main(String[] args) {

        metricRegistry.register(
                MetricRegistry.name(SimpleGauge.class, "queue-size"),
                new Gauge<Integer>() {
                    // 通过返回一个Value，创建一个最简洁的Gauge
                    @Override
                    public Integer getValue() {
                        return queue.size();
                    }
                });

        // 启动后，就能够实时的获取Gauge所返回的内容
        reporter.start(2, TimeUnit.SECONDS);


        // 往队列中加数据
        new Thread(() -> {
            for (; ; ) {
                randomSleep();
                queue.add(System.nanoTime());
            }
        }).start();

        // 从队列中取数据
        new Thread(() -> {
            for (; ; ) {
                randomSleep();
                queue.poll();
            }
        }).start();
    }

}
